/*
 * 作者:熊猫
 * 日期:2017 - 3 - 19 7 - 0 - 43
 *
 */

package net.lainiao.morethread.Chapter7.demo6;

import java.util.concurrent.RecursiveTask;

/**
 * Created by Administrator on 2017/3/19.
 */
public class MyRecursiveTask extends RecursiveTask<Integer> {
    private int[] array;
    private int start, end;

    public MyRecursiveTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        MyWorkerThread thread = (MyWorkerThread) Thread.currentThread();
        thread.addTask();
        if(end-start<1000000){
            int temRes=0;
            for (int i = start; i <end ; i++) {
                temRes+=array[i];
            }
            return temRes;
        }
        int middle=start+(end-start)/2;
        MyRecursiveTask task1 = new MyRecursiveTask(array, start, middle);
        MyRecursiveTask task2 = new MyRecursiveTask(array, middle, end);
        int result = addResults(task1, task2);
        return result;
    }

    private Integer  addResults(MyRecursiveTask task1, MyRecursiveTask task2) {
        int value;
        task1.fork();
        task2.fork();
        value = task1.join() + task2.join();
        return value;
    }
}
